package com.gec.provider;

import com.gec.dao.UserInfoDao;
import com.gec.domain.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component("MyUserDetailService")
public class MyUserDetailService implements UserDetailsService {

    @Autowired
    private UserInfoDao userInfoDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserInfo userInfo = null;
        User user = null;

        if (username != null) {
            //如果输入的用户名不为空则从数据库中查询该用户信息
            userInfo = userInfoDao.findByUsername(username);

            if (userInfo != null) {
                //如果查询的信息不为空则构建User

                //角色列表
                List<GrantedAuthority> roles = new ArrayList<>();

                //添加角色必须以ROLE_开头
                GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_" + userInfo.getRole());
                roles.add(authority);

                //构建User
                user = new User(userInfo.getUsername(), userInfo.getPassword(), roles);
            }
        }
        return user;
    }
}
